<template>
  <div>  
    <!-- 页面表格数据渲染 -->
    <en-table-layout toolbar pagination :loading="loading" :tableData="tableData">
        <div slot="toolbar" class="inner-toolbar">
          <div class="toolbar-btns">
            <!-- 顶部五个按钮 -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-circle-plus-outline"
              @click="handleLeader()"
            >添加</el-button>
            <!-- <el-button size="mini" type="primary" @click>启用</el-button>
            <el-button size="mini" type="primary" @click>禁用</el-button>
            <el-button size="mini" type="primary" @click>营业</el-button>
            <el-button size="mini" type="primary" @click>打烊</el-button> -->
          </div>
          <div class="toolbar-search">
            <!-- 顶部搜索栏 -->
            <en-table-search
              @search="searchEvent"
              @advancedSearch="advancedSearchEvent"
              advanced
              advancedWidth="465"
              placeholder="请输入关键字">
              <template slot="advanced-content">
                <el-form ref="advancedForm" :model="advancedForm"  label-width="80px">              
                  <el-form-item label="营业状态" class="toolbar-input" prop="op_status">
                    <el-select v-model="advancedForm.op_status" placeholder="请选择营业状态" class="select-get" clearable>
                      <el-option label="休息中" :value="0"></el-option>
                      <el-option label="营业中" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所在地区" class="toolbar-input" prop="region">
                    <en-region-picker
                      :api="MixinRegionApi"
                      :default="advancedForm.areas"
                      @changed="(object) => { advancedForm.region = object.last_id }"
                      class="select-get"
                      clearable
                    ></en-region-picker>
                  </el-form-item>
                  <el-form-item label="站点类型" class="toolbar-input" prop="site_type">
                      <el-select v-model="advancedForm.site_type" placeholder="请选择站点类型" class="select-get" clearable>
                        <el-option
                          v-for="option in s_site_type"
                          :label="option.name"
                          :value="option.id"
                          :key="option.id"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  <el-form-item label="团长类型" class="toolbar-input" prop="leader_type">
                    <el-select v-model="advancedForm.leader_type" class="select-get" clearable>
                      <el-option label="虚拟团长" :value="0"></el-option>
                      <el-option label="真实团长" :value="1"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="团长状态" class="toolbar-input" prop="status">
                      <el-select v-model="advancedForm.status" placeholder="请选择团长状态" class="select-get" clearable>
                        <el-option label="已禁用" :value="0"></el-option>
                        <el-option label="启用中" :value="1"></el-option>
                      </el-select>
                  </el-form-item>
                </el-form>
              </template>
            </en-table-search>
          </div>     
        </div>
      <!-- 列表渲染 -->
      <template slot="table-columns">
        <el-table-column type="selection" min-width="50"></el-table-column>
        <el-table-column prop="leader_id" min-width="80" label="团长编号" />
        <el-table-column prop="leader_name" min-width="100" label="团长姓名" />
        <el-table-column prop="leader_mobile" min-width="150" label="联系电话" />
        <el-table-column label="团长类型" min-width="80">
          <template slot-scope="scope">
            <span>{{scope.row.leader_type==1?"真实团长":"虚拟团长"}}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="level" min-width="80" label="团长等级"/> -->
        <el-table-column label="团长状态">
          <template slot-scope="scope">
            <span>{{scope.row.status==1?"启用":"禁用"}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="leader_name" min-width="100" label="团长姓名" />
        <el-table-column prop="leader_mobile" min-width="150" label="联系电话" />
        <el-table-column label="营业状态" >
         <template slot-scope="scope">
            <span>{{scope.row.op_status==1?"营业中":"休息中"}}</span>
          </template>
         </el-table-column>
        <el-table-column prop="member_id" min-width="80" label="关联用户" />
        <el-table-column prop="cell_name" min-width="100" label="小区名称" />
        <el-table-column prop="province" min-width="100" label="联系地址" />
        <el-table-column prop="site_name" min-width="100" label="站点名称" />
        <el-table-column min-width="100" label="站点类型">
          <template slot-scope="scope">
            <span>{{site[scope.row.site_type]}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="140" label="申请时间">
          <template
            slot-scope="scope"
          >{{ scope.row.update_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</template>
        </el-table-column>
        <el-table-column min-width="140" label="加入时间">
          <template slot-scope="scope">{{ scope.row.add_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</template>
        </el-table-column>
        <el-table-column min-width="140" label="创建时间">
          <template slot-scope="scope">{{ scope.row.add_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</template>
        </el-table-column>
        <el-table-column prop="creater_name" min-width="100" label="创建人" />
        <!-- <el-table-column min-width="100" label="修改时间">
          <template
            slot-scope="scope"
          >{{ scope.row.update_time | unixToDate("yyyy-MM-dd hh:mm:ss") }}</template>
        </el-table-column> -->
        <!-- <el-table-column prop="leader_mobile" min-width="100" label="修改人" /> -->
        <el-table-column label="操作" min-width="180" fixed="right">
          <template slot-scope="scope" >
            <el-button type="primary" @click="handleLeader(scope.row)">修改</el-button>
            <el-button type="danger" @click="deleteLeaderList(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </template>
      <!-- 分页列表 -->
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total"
      ></el-pagination>
    </en-table-layout>

    <!--对话框用来添加修改团长信息-->
    <el-dialog
        :title="titleMap[dialogTitle]"
        :visible.sync="DialogVisible"
        width="500px"
        :append-to-body="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
      <div class="infomation">基本信息</div>
      <!-- 主体区域 左侧距离-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- <el-form-item label="团长编码" prop="leader_id">
          <el-input v-model="addForm.leader_id"></el-input>
        </el-form-item>-->
        <el-form-item label="团长姓名" prop="leader_name">
          <el-input v-model="addForm.leader_name" class="select-type" clearable></el-input>
        </el-form-item>
        <el-form-item label="团长类型" prop="leader_type">
          <el-select v-model="addForm.leader_type" value="0" class="select-type" clearable>
            <el-option label="虚拟团长" :value="0"></el-option>
            <el-option label="真实团长" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联用户" prop="member_id">
          <el-select
            v-model="addForm.member_id"
            filterable
            remote
            placeholder="请输入关键词"
            clearable
            :remote-method="remoteMethod"
            :loading="remote_loading"
            class="select-type"
          >
            <el-option
              v-for="item in options"
              :key="item.member_id"
              :label="item.mobile"
              :value="item.member_id"
            >
              <span>{{item.nickname}}</span>
              <span class="mobile">{{item.mobile}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小区名称" prop="cell_name">
          <el-input v-model="addForm.cell_name" class="select-type" placeholder="请输入小区名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <en-region-picker
            :api="MixinRegionApi"
            :default="areas"
            @changed="(object) => { addForm.region = object.last_id }"
            class="select-type"
            clearable
          ></en-region-picker>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addForm.address" class="select-type" placeholder="请输入详细地址" clearable></el-input>
        </el-form-item>
        <!--高德地图-->
        <el-form-item prop="map">
          <div class="map">
            <div id="mapContainer" style="height:250px;width:300px;"></div>
            <input type="text" id="mapInput" class="map-search" clearable placeholder="请输入店铺地址" />
          </div>
        </el-form-item>
        <div class="infomation">站点信息</div>
        <el-form-item label="站点名称" prop="site_name">
          <el-input v-model="addForm.site_name" class="select-type" placeholder="请输入站点名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="站点类型" prop="site_type">
          <el-select v-model="addForm.site_type" class="select-type" clearable>
            <el-option
              v-for="option in s_site_type"
              :label="option.name"
              :value="option.id"
              :key="option.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="胜任理由" prop="join_reason">
          <el-input
            v-model="addForm.join_reason"
            class="select-type"
            placeholder="请输入胜任理由"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <div class="footer">
        <div class="infooter">
          <el-button type="primary" @click="verify()">{{titleFoot[dialogTitle]}}</el-button>
          <el-button @click="DialogVisible=false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_LEADER from '@/api/leader';
import AMap from 'AMap';
import * as API_Shop from '@/api/shop';
import { UE } from '@/components';

let map = null; // 地图
let marker = null; // 自定义标记点
export default {
  name: 'leaderList',
  components: {
    [UE.name]: UE
  },
  data() {
    return {
      // 基本公用数据
      loading: false,
      remote_loading: false,
      site: ['快递站', '便利店', '小卖部', '小超市', '洗衣店', '其他'],
      // 关联用户用到的数据
      options: [],
      value: [],
      list: [],
      states: [],
      //团长等级下拉框
      s_leader_level: [
        { id: '0', name: '运营经理' },
        { id: '1', name: '运营总监' },
        { id: '2', name: '事业合伙人' },
        { id: '3', name: '联合创始人' }
      ],
      //站点类型下拉框
      s_site_type: [
        { id: '0', name: '快递站' },
        { id: '1', name: '便利店' },
        { id: '2', name: '小卖部' },
        { id: '3', name: '小超市' },
        { id: '4', name: '洗衣店' },
        { id: '5', name: '其他' }
      ],
      // 对话框数据
      DialogVisible: false,
      deletedialogVisible: false,
      dialogTitle: '',
      titleMap: {
        addData: '新增团长',
        updateData: '修改团长'
      },
      titleFoot: {
        addData: '确认新增',
        updateData: '确认修改'
      },
      // 添加表单内的数据
      addForm: {
        //团长编号
        // leader_id: '',
        // 团长姓名
        leader_name: '',
        //团长类型
        leader_type: '',

        //关联用户
        member_id: '',

        //小区名称
        cell_name: '',

        // 所在地区
        region: '',

        //详细地址
        address: '',

        // 站点名称
        site_name: '',

        //站点类型
        site_type: '',

        //胜任理由
        join_reason: '',

        //经纬度
        lng: '',
        lat: ''
      },
      //查询表单内的数据
      advancedForm: {
        //关键字
        keyword: '',
        // 营业状态
        op_status: '',
        // 所在地区
        region: '',
        // 站点类型
        site_type: '',
        // 站点类型
        member_id: '',
        // 团长类型
        leader_type: '',
        // 团长状态
        status: '',
        areas: []
      },
      // 分页参数配置
      params: {
        page_no: 1,
        page_size: 10
      },
      // 添加表单验证
      addFormRules: {
        // leader_id: [
        //   { required: true, message: '请输入团长编号', trigger: 'blur' }
        // ],
        leader_name: [
          { required: true, message: '请输入团长姓名', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        leader_type: [
          { required: true, message: '请选择团长类型', trigger: 'change' }
        ],
        member_id: [{ required: true, message: '请输入内容', trigger: 'change' }],
        cell_name: [
          { required: true, message: '请输入小区名称', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请输入所在地区', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        site_name: [
          { required: true, message: '请输入站点名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        site_type: [
          { required: true, message: '请选择站点类型', trigger: 'change' }
        ],
        join_reason: [
          { required: true, message: '请输入胜任理由', trigger: 'blur' }
        ]
      /** 地图点位 */
        // map: [
        //   { required: true, message: '请设置有效的地图点位', trigger: 'change' }
        // ]
      },
      
      areas: [],
      /** 列表数据 */
      tableData: [],
      /** 列表分页数据 */
      pageData: [],
      /** 当前发票所关联的商品列表信息 */
      leaderList: []
    };
  },
  mounted() {
    this.getLeaderList();
  },

  methods: {
    /**
     * @date 2020/06/13
     * @author kjh
     * @description {点击添或者修改团长信息}
     */
    handleLeader(row) {
      this.DialogVisible = true;
      if (row===undefined) {
        this.dialogTitle = 'addData';
        this.$nextTick(async () => {
          await this.initMap();
          this.$nextTick(() => {
            setTimeout(this.initAutocomplete(), 10000);
          });
          this.resetAdd();
          this.areas = [];
        });
      }
      else {
        this.dialogTitle = 'updateData';
        // 传入团长编号
        this.$nextTick(async () => {
          this.resetAdd();
          await this.initMap();
          this.$nextTick(() => {
            setTimeout(this.initAutocomplete(), 10000);
          });
          this.askLeaderDetail(row.leader_id);
        });
      }
    },
    //表单验证 发送提交信息
    verify() {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          if (this.dialogTitle === 'addData') {
            this.loading = true;
            API_LEADER.addLeaderList(this.addForm)
              .then(response => {
                this.loading = false;
                this.DialogVisible = false;
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
                this.getLeaderList();
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            this.loading = true;
            API_LEADER.updateLeaderList(this.addForm)
              .then(response => {
                this.loading = false;
                this.DialogVisible = false;
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getLeaderList();
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } 
      });
    },

    /** 接口相关方法 */
    /**
     * @date 2020/06/12
     * @author kjh
     * @description { 页面初始化团长信息 }
     */
    getLeaderList() {
      this.loading = true;
      API_LEADER.getLeaderList(this.params)
        .then(response => {
          this.loading = false;
          this.tableData = response.data;
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          };
        })
        .catch(() => {
          this.loading = false;
        });
    },
    /**
     * @date 2020/06/13
     * @author kjh
     * @description { 修改时查询详情列表信息 }
     */
    askLeaderDetail(id) {
      this.loading = true;
      API_LEADER.askLeaderList(id)
        .then(response => {
          this.loading = false;
          const { leader, member } = response;
          this.options = [
            {
              nickname: member.nickname,
              mobile: member.mobile,
              member_id: member.member_id
            }
          ];
          this.areas = [
            leader.province_id,
            leader.city_id,
            leader.county_id || -1,
            leader.town_id || -1
          ];
          this.$nextTick(() => {
            this.addForm = leader;
            this.addForm.site_type = this.addForm.site_type + '';
            const _lng = leader.lng;
            const _lat = leader.lat;
            if (_lng || _lat) {
              let _position = new AMap.LngLat(_lng, _lat);
              this.showMapMarker(_position);
            }
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * @date 2020/06/12
     * @author kjh
     * @description { 发送查询会员请求 }
     */
    getMemberList(query) {
      this.remote_loading = true;
      let params = {
        keyword: query,
        page_no: 1,
        page_size: 999
      };
      API_LEADER.getMemberList(params)
        .then(response => {
          this.remote_loading = false;
          this.options = response.data;
        })
        .catch(() => {
          this.remote_loading = false;
        });
    },

    /**
     * @date 2020/06/11
     * @author kjh
     * @description { 发送删除请求 }
     */
    async deleteLeaderList(row) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！');
      }
      API_LEADER.deleteLeaderList(row.leader_id)
        .then(response => {
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getLeaderList();
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * @date 2020/06/14
     * @author kjh
     * @description { 重置添加修改表单数据和校验规则 }
     */
    resetAdd() {
      if (this.$refs.addFormRef !== undefined){
        this.$refs.addFormRef.resetFields();
        this.areas = [];
      }
    },

    /**
     * @date 2020/06/14
     * @author kjh
     * @description { 远程搜索 }
     */
    remoteMethod(query) {
      if (query !== '') {
        this.getMemberList(query);
      } else {
        this.options = [];
      }
    },

    /*
     * @date 2020-02-16
     * @author wolfMan
     * @description {初始化地图}
     */
    initMap() {
      // 初始化地图
      map = new AMap.Map('mapContainer', {
        resizeEnable: true,
        zoom: 16
      });
      // 生成自定义标记点
      marker = new AMap.Marker({
        position: map.getCenter(),
        cursor: 'move',
        raiseOnDrag: true, // 标记点拖拽
        offset: new AMap.Pixel(-13, -30) // 以 icon 的 [center bottom] 为原点
      });
      // 生成地图内自动填充输入框
      const placeSearch = new AMap.PlaceSearch({ map: map });
      marker.setMap(map);
      // map点击事件生成自定义标记点
      map.on('click', e => {
        this.setAddress(e.lnglat);
        marker.setPosition(e.lnglat);
      });
      // 点击标记点选择地址
      placeSearch.on('markerClick', e => {
        this.setAddress(e.event.lnglat);
      });
      // 添加插件到map上
      AMap.plugin(
        ['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch'],
        function() {
          map.addControl(new AMap.PlaceSearch());
          map.addControl(new AMap.ToolBar());
          map.addControl(new AMap.Scale());
        }
      );
    },

    /*
     * @date 2020-02-16
     * @author wolfMan
     * @description {设置地图标点}
     */
    showMapMarker(_lnglat) {
      map.setCenter(_lnglat);
      marker.setPosition(_lnglat);
    },

    /*
     * @date 2020-02-16
     * @author wolfMan
     * @description {自动填充地址}
     */
    setAddress(lnglat) {
      const geocoder = new AMap.Geocoder();
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const {
            regeocode: {
              formattedAddress,
              addressComponent: { province, city, district }
            }
          } = result;
          if (!this.addForm.add || this.addForm.add.trim() === '') {
            this.$set(this.addForm, 'add', formattedAddress);
          }
          this.$set(this.addForm, 'lng', lnglat.lng);
          this.$set(this.addForm, 'lat', lnglat.lat);
          this.$set(this.addForm, 'map', [lnglat.lng, lnglat.lat]);
        }
      });
    },

    /*
     * @date 2019-12-06
     * @author wolfMan
     * @description {自动匹配地址选项}
     */
    initAutocomplete() {
      const mapAutoComplete = new AMap.Autocomplete({ input: 'mapInput' });
      mapAutoComplete.on('select', res => {
        if (res.poi.location) {
          const _location = res.poi.location;
          this.setAddress(_location);
          let _position = new AMap.LngLat(_location.lng, _location.lat);
          this.showMapMarker(_position);
        } else {
          this.$message.warning('您选择的地址不是一个具体的地址');
        }
      });
    },

    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.getLeaderList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.getLeaderList();
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        ...this.advancedForm,
        keyword: data
      };
      this.getLeaderList();
    },
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm
      };
      this.getLeaderList();
    }
  }
};
</script>

<style type="text/scss" lang="scss" scoped>
//顶部工具栏样式
.inner-toolbar{
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
  }

//基本信息和站点信息
.infomation {
  font-size: 15px;
  font-weight: bold;
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid;
}

//地图和所在地区组件
/deep/ .app-address {
  width: 100% !important;
  height: 32px;
  .app-address-title {
    padding: 0 20px 0 15px;
    height: 32px;
    line-height: 32px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
  }
}

//高德地图
.map {
  position: relative;
  width: 500px;
  .map-search {
    position: absolute;
    top: 15px;
    right: 15px;
    padding: 5px 10px;
    width: 300px;
    line-height: 22px;
    border: none;
    border-radius: 4px;
    outline: none;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
    overflow: hidden;
  }
}

//设置对话框两个按钮居中
.footer {
  display: flex;
  justify-content: center;
}

//设置高德地图输入框位置和尺寸
.map .map-search {
  width: 200px;
  left: 60px;
}

.select-get{
  width: 100%;
}

//设置对话框内的输入框宽度
.select-type {
  width: 300px;
}

//设置远程搜索(关联用户)左右对齐
.mobile {
  float: right;
}
</style>

<style type="text/scss" lang="scss">
.toolbar-input .el-form-item__label {
  font-weight: normal;
}

//显示高德地图输入框提示
.amap-sug-result {
  z-index: 9999;
}
</style>